package edu.stu.software.family.RabbitMQ;

import java.io.IOException;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

import edu.stu.software.family.file.writer.ParsingUtil;
import edu.stu.software.family.people.domain.People;
import edu.stu.software.family.people.mapper.PeopleMapper;
import edu.stu.software.family.people.mapper.impl.PeopleMapperImpl;
/**
 * 
 * @author liu_pan_ting
 *
 */
 public class MQGet {
    private final static String QUEUE_NAME = "/";
    private static People people = null;
    private static PeopleMapper pm = new PeopleMapperImpl();
    /**
     *  
     */
     public static void getMsg() throws Exception{
       
        Connection connection = MQContUtils.getConnection();
        
        final Channel channel = connection.createChannel();
        
        channel.queueDeclare(QUEUE_NAME, false, false, false, null);

        DefaultConsumer consumer = new DefaultConsumer(channel){
             @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String msg = new String(body);
                System.out.println("information is :"+msg);
                if (msg.contains(".txt"))
                    people = ParsingUtil.parsingTxt(msg);
                else if (msg.contains(".xlsx"))
                    people = ParsingUtil.parsingExcel(msg);
                else
                    people = ParsingUtil.parsingJSON(msg);

                int add = pm.add(people);
                if (add > 0)
                    System.out.println("information of people add success!");
                else
                    System.out.println("defeat!");
               
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        };
           
        // utoAck = false
        channel.basicConsume(QUEUE_NAME, false, consumer);
    }

    public static void main(String[] args) throws Exception{
        getMsg();
    }
}
